<template>
	<div class="pagination">
		<ul>
			<li @click="prevPage">
				<button :disabled="page <= 1">&lt;</button>
			</li>
			<li v-for="p in pages" :key="p" :class="{ active: p === page }" @click="changePage(p)">{{
				p }}</li>
			<li @click="nextPage">
				<button :disabled="page >= totalPages">&gt;</button>
			</li>
		</ul>
	</div>
</template>
  
<script>
export default {
	name: "Pagination",
	props: {
		total: {
			type: Number,
			required: true
		},
		onChange: {
			type: Function,
			required: true
		}
	},
	data() {
		const pageSize = 5;
		return {
			page: 1,
			pageSize,
			totalPages: Math.ceil(this.total / pageSize)
		};
	},
	watch: {
		total() {
			this.totalPages = Math.ceil(this.total / this.pageSize);
		}
	},
	computed: {
		pages() {
			const pages = [];
			for (let i = 1; i <= this.totalPages; i++) {
				pages.push(i);
			}
			return pages;
		}
	},
	methods: {
		prevPage() {
			this.page--;
			this.onChange({ page: this.page });
		},
		nextPage() {
			this.page++;
			this.onChange({ page: this.page });
		},
		changePage(page) {
			this.page = page;
			this.onChange({ page: this.page });
		}
	}
};
</script>
<style lang="less" scoped>
.pagination,
ul {
	display: flex;
	align-items: center;

	li,
	button {
		cursor: pointer;
	}

	.active {
		color: blueviolet;
	}
}

li {
	padding: 10px;
}
</style>
  